<template>
  <!-- 选择关联服务弹窗 -->
  <div>
    <el-dialog v-model="dialogVisible" title="服务目录" width="600px">
      <div v-loading="loading">
        <el-tree ref="serveTree" :props="props" :load="loadNode" lazy show-checkbox />
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="SelectServesMask">
import { ref } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { getCategoryTree } from "@/api/modules/common";

interface Tree {
  id: number;
  eventId: string;
  cname: string;
  children?: Tree[];
  level: number;
}

const props = {
  label: "cname",
  children: "children"
};

const loading = ref(false);

const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
  if (node.level === 0) {
    loading.value = true;
    getCategoryTree({
      _: new Date().getTime(),
      num: 0,
      types: "Service",
      parentEventId: 0
    })
      .then((res: any) => {
        loading.value = false;
        resolve([
          {
            ...res.attr,
            children: res.children,
            level: 0
          }
        ]);
      })
      .catch(() => {
        loading.value = false;
      });
  } else if (node.level === 1) {
    let arr1 = node.data.children || [];
    let list = ref<Tree[]>([]);
    arr1.forEach(item => {
      list.value.push({
        ...item.attr,
        children: item.children,
        level: 1
      });
    });
    resolve(list.value);
  } else if (node.level === 2) {
    getCategoryTree({
      _: new Date().getTime(),
      num: 0,
      types: "Service",
      parentEventId: node.data.id
    }).then((res: any) => {
      let arr2 = ref<Tree[]>([]);
      res.forEach(item => {
        arr2.value.push({
          ...item.attr,
          children: [],
          level: 2
        });
      });
      resolve(arr2.value);
    });
  } else {
    resolve([]);
  }
};

const dialogVisible = ref(false);

// 定义 emit 事件
const emit = defineEmits<{
  (e: "change", serves: Tree[]): void;
}>();

const serveTree = ref();
const submit = () => {
  let list = serveTree.value.getCheckedNodes();
  let fids = ref<any[]>([]);
  list.forEach((item: Tree) => {
    if (fids.value.length == 0 || fids.value.indexOf(item.eventId) < 0) {
      fids.value.push(item.eventId);
    }
  });
  let serves = ref<Tree[]>([]);
  list.forEach((item: Tree) => {
    if (fids.value.indexOf(item.id) < 0) {
      serves.value.push(item);
    }
  });

  dialogVisible.value = false;
  emit("change", serves.value);
};

const open = () => {
  dialogVisible.value = true;
};

defineExpose({
  open
});
</script>
